﻿using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using YXChatApiService.Application;
using YXChatApiService.Application.AccountServices;
using YXChatApiService.Application.AccountServices.Dtos;
using YXChatApiService.Application.BuddyServices;
using YXChatApiService.Application.BuddyServices.Dtos;
using YXChatApiService.Core.AccountEntity.DomainManager;
using YXChatApiService.Filters;

namespace YXChatApiService.Controllers
{
    public class AccountController : ApiControllerBase
    {
        private readonly IAccountAppService _accountAppService;
        private readonly IAccountManager _accountManager;
        private readonly IBuddyAppService _buddyAppService;
        private readonly IWebHostEnvironment _webHostEnvironment;
        public AccountController(IAccountAppService accountAppService, IWebHostEnvironment webHostEnvironment, IAccountManager accountManager, IBuddyAppService buddyAppService)
        {
            _accountAppService = accountAppService;
            _webHostEnvironment = webHostEnvironment;
            _accountManager = accountManager;
            _buddyAppService = buddyAppService;
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultDto<AccountDto>> Register(AccountEditDto input)
        {
            ResultDto<AccountDto> result = new ResultDto<AccountDto>();
            var account = await _accountAppService.CreateOrUpdate(input);
            if (account==null)
            {
                result.Success = false;
                result.Msg = "一个电话号码只能注册一个账户";
                return result;
            }
            result.Success = true;
            result.Data = account;
            BuddyCreateOrUpdateInput refBuddy = new BuddyCreateOrUpdateInput()
            {
                AdderAccountNumber = account.AccountNumber,
                AddeeAccountNumber = "admin",
                IsAgree = true
            };
            await _buddyAppService.CreateOrUpdateBuddy(refBuddy);
            return result;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [ResultDataFilter]
        public async Task<AccountDto> Login(LoginInput input)
        {
            return await _accountAppService.GetAccount(input);
        }
        /// <summary>
        /// id获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [ResultDataFilter]
        public AccountDto Get(Guid id)
        {
            return _accountAppService.Get(id);
        }
        /// <summary>
        /// yx号码获取用户信息
        /// </summary>
        /// <param name="accountNumber"></param>
        /// <returns></returns>
        [HttpGet("{accountNumber}")]
        [ResultDataFilter]

        public AccountDto GetAccountByNumber(string accountNumber)
        {
            return _accountAppService.GetAccount(accountNumber);
        }
        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <param name="dto"></param>
        [HttpPost]
        [ResultDataFilter]
        public async Task<string> UpdateAccountAvatar(UpdateAvatarDto dto)
        {
            // 将base64转为字节数组
            byte[] bytes = Convert.FromBase64String(dto.AvatarBase64);
            var imgUrl = $"imgs/{dto.AccountNumber}.png";
            string filePath = Path.Combine(_webHostEnvironment.WebRootPath,$"imgs/{dto.AccountNumber}.png");
            string dirPath = Path.Combine(_webHostEnvironment.WebRootPath, "imgs");
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            // 将字节写入文件
            await System.IO.File.WriteAllBytesAsync(filePath, bytes);
            await _accountAppService.UpdateAccountAvatar(dto.AccountNumber, imgUrl);
            return imgUrl;
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ResultDataFilter]
        public async Task<UpdateAccountOutput> UpdateAccount(AccountEditDto dto)
        {
            var oldEntity = _accountManager.QueryAsNoTracking.FirstOrDefault(x => x.AccountNumber == dto.AccountNumber);
            var newEntity= await _accountAppService.CreateOrUpdate(dto);
            return new UpdateAccountOutput()
            {
                IsUpdatePwd = !(oldEntity != null && oldEntity.PassWord == dto.PassWord),
                Account = newEntity
            };
        }
        [HttpGet("{accountId}")]
        [ResultDataFilter]
        public async Task<string> GetAccountPassWord(Guid accountId) 
        {
            return await _accountAppService.GetAccountPassWord(accountId);
        }

        /// <summary>
        /// HttpClient预热
        /// </summary>
        [Route("/")]
        [HttpHead]
        public void Test()
        {

        }
    }
}